<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>实现input表单和object对象的一个属性的双向数据绑定</title>
  <style type="text/css">
   body {
    padding: 50px;
    background: #34495e;
  }
  input {
    border: solid 10px #ddd;
    height: 30px;
  }
  .error {
    border: solid 10px red;
  }
  </style>
</head>
<body>
  <div id="box" class="box">
    <input type="text" validate rule="max:12,min:3" />
  <input type="text" validate rule="max:3,isNumber" />
  </div>
  <script src="https://cdn.staticfile.org/jquery/3.2.0/jquery.js"></script>
  <script type="text/javascript">
 "use strict";
  //验证处理类
  class Validate {
    max(value, len) {
      return value.length <= len;
    }
    min(value, len) {
      return value.length >= len;
    }
    isNumber(value) {
      return /^\d+$/.test(value);
    }
  }
    //代理工厂
  function makeProxy(target) {
    var proxy = new Proxy(target, {
      get(target, property) {
          return target[property]
      },
      set(target, property, el) {
          const rule = el.getAttribute('rule')
          const validate = new Validate()

          let state = rule.split(',').every(r => {
            let [fn, val] = r.split(":")
            return validate[fn](el.value.trim(), val)
          })
          el.classList[state ? 'remove' : 'add']('error')
          return true;
      }
    })
    return proxy
  }


  const nodes = makeProxy(document.querySelectorAll("[validate]"))

  nodes.forEach((item, i) => {
    item.addEventListener('keyup', function(evt) {
      nodes[i] = this
    })
  })


  </script>
</body>
</html>